﻿using UnityEngine;

namespace FSM.PlayerState
{
    public class PlayerFreeLookState : PlayerBaseState
    {
        private static readonly int FreeLookSpeed = Animator.StringToHash("FreeLookSpeed");
        // private float elapseTime;
        
        public PlayerFreeLookState(PlayerStateMachine stateMachine) : base(stateMachine)
        {
        }


        public override void Enter()
        {
            Debug.Log($"PlayerState : Enter: {this}");
            
            // stateMachine.InputReader.JumpEvent += OnJump;
        }

        private void OnJump()
        {
            stateMachine.SwitchState(new PlayerFreeLookState(stateMachine));
        }

        public override void Tick(float deltaTime)
        {
            // elapseTime += Time.deltaTime;

            // Debug.Log($"PlayerState : Tick: {elapseTime}");
            // if (elapseTime > 5.0f)
            // {
            //     elapseTime = 0;
            //     stateMachine.SwitchState(new PlayerState(stateMachine));
            // }

            // var value = stateMachine.InputReader.MovementValue;
            // base on world position
            // Vector3 movement = new Vector3(value.x, 0, value.y);
            
            // base on camera direction
            Vector3 movement = GetCameraMovement();
            
            // stateMachine.transform.Translate(movement * deltaTime);
            stateMachine.CharControl.Move(movement * stateMachine.FreeLookMoveSpeed * deltaTime);
            // Debug.Log($"Move: {stateMachine.InputReader.MovementValue}");

            var moveDirection = stateMachine.InputReader.MovementValue.magnitude;
            if (moveDirection < float.Epsilon)
            {
                stateMachine.Animator.SetFloat(FreeLookSpeed, 0f);
                return;
            }
            
            // 按下了方向 
            stateMachine.Animator.SetFloat(FreeLookSpeed, moveDirection, 0.1f, deltaTime);
            
            // 朝向移动的方向， 转向是一个过程
            FaceMovementDirection(movement, deltaTime);
        }

        private Vector3 GetCameraMovement()
        {
            var forward = stateMachine.MainCameraTransform.forward;
            var right = stateMachine.MainCameraTransform.right;
            forward.y = 0;
            right.y = 0;
            forward.Normalize();
            right.Normalize();
            var value = stateMachine.InputReader.MovementValue;
            return forward * value.y + right * value.x;
        }

        public override void Exit()
        {
            Debug.Log($"PlayerState : Exit: {this}");
            
            // stateMachine.InputReader.JumpEvent -= OnJump;
        }

        private void FaceMovementDirection(Vector3 movement, float deltaTime)
        {
            stateMachine.gameObject.transform.rotation = Quaternion.Lerp(stateMachine.gameObject.transform.rotation, Quaternion.LookRotation(movement), deltaTime * stateMachine.RotationDamp);
        }
    }
}